package online.chazi.bootplus.commons.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.util.TypeUtils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 说明：作者很懒，什么都没留下
 * Created by 叉子同学 on 2020-03-06 18:48
 */
public class MapUtils<T, V> extends HashMap<T, V> {

    public static <T, V> MapUtils<T, V> build() {
        return new MapUtils<>();
    }

    public MapUtils<T, V> add(T key, V value) {
        this.put(key, value);
        return this;
    }

    public Date getDate(T key) {
        return TypeUtils.castToDate(this.get(key));
    }

    public static Map<String, Object> fromBean(Object object) {
        Map<String, Object> result = new HashMap<>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
            PropertyDescriptor[] propertyDescriptor = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptor) {
                String key = property.getName();
                if (key.compareToIgnoreCase("class") == 0) {
                    continue;
                }
                Method getter = property.getReadMethod();
                Object value = getter != null ? getter.invoke(object) : null;
                result.put(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }

}
